<!DOCTYPE html>
<html class="ui-page-login">

	<head>
		<meta charset="utf-8">
		<meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no" />
		<title></title>
		<link href="../../static/css/mui.min.css" rel="stylesheet" />
		<link href="../../static/css/style.css" rel="stylesheet" />
		<style>
			.area {
				margin: 20px auto 0px auto;
			}
			
			.mui-input-group {
				margin-top: 10px;
			}
			
			.mui-input-group:first-child {
				margin-top: 20px;
			}
			
			.mui-input-group label {
				width: 22%;
			}
			
			.mui-input-row label~input,
			.mui-input-row label~select,
			.mui-input-row label~textarea {
				width: 78%;
			}
			
			.mui-checkbox input[type=checkbox],
			.mui-radio input[type=radio] {
				top: 6px;
			}
			
			.mui-content-padded {
				margin-top: 25px;
			}
			
			.mui-btn {
				padding: 10px;
			}
			
			.link-area {
				display: block;
				margin-top: 25px;
				text-align: center;
			}
			
			.spliter {
				color: #bbb;
				padding: 0px 8px;
			}
			
			.oauth-area {
				position: absolute;
				bottom: 20px;
				left: 0px;
				text-align: center;
				width: 100%;
				padding: 0px;
				margin: 0px;
			}
			
			.oauth-area .oauth-btn {
				display: inline-block;
				width: 50px;
				height: 50px;
				background-size: 30px 30px;
				background-position: center center;
				background-repeat: no-repeat;
				margin: 0px 20px;
				/*-webkit-filter: grayscale(100%); */
				border: solid 1px #ddd;
				border-radius: 25px;
			}
			
			.oauth-area .oauth-btn:active {
				border: solid 1px #aaa;
			}
			
			.oauth-area .oauth-btn.disabled {
				background-color: #ddd;
			}
		</style>

	</head>

	<body>
		<header class="mui-navbar-inner mui-bar mui-bar-nav" style="background-color: #EFEFF4;">
			<button type="button" class="mui-left mui-action-back mui-btn  mui-btn-link mui-btn-nav mui-pull-left">
				<span class="mui-icon mui-icon-left-nav"></span>我的
			</button>
			<h1 class="mui-title">登录</h1>
		</header>
		<div class="mui-content">
			<form id='login-form' class="mui-input-group">
				<div class="mui-input-row">
					<label>账号</label>
					<input id='uname' type="text" class="mui-input-clear mui-input" placeholder="请输入账号">
				</div>
				<div class="mui-input-row">
					<label>密码</label>
					<input id='password' type="password" class="mui-input-clear mui-input" placeholder="请输入密码">
				</div>
			</form>
			<form class="mui-input-group">
				<ul class="mui-table-view mui-table-view-chevron">
					<li class="mui-table-view-cell">
						自动登录
						<div id="autoLogin" class="mui-switch">
							<div class="mui-switch-handle"></div>
						</div>
					</li>
				</ul>
			</form>
			<div class="mui-content-padded">
				<button id='login' class="mui-btn mui-btn-block mui-btn-primary">登录</button>
				<div class="link-area"><a id='reg'>注册账号</a> <span class="spliter">|</span> <a id='forgetPassword'>忘记密码</a>
				</div>
			</div>
			<div class="mui-content-padded oauth-area">

			</div>
		</div>
		<script src="../../static/js/mui.min.js"></script>
		<script src="../../static/js/mui.enterfocus.js"></script>
		<script src="../../static/js/app.js"></script>
		<script>
		(function($, doc) {
			$.init({
				swipeBack: true, //启用右滑关闭功能
				//statusBarBackground: '#f7f7f7',
			});

			$.plusReady(function() {
				plus.screen.lockOrientation("portrait-primary");
				var settings = app.getSettings();
				var state = app.getState();

				var userweb = plus.webview.getWebviewById('settingpage');

				var toUser = function() {
					$.fire(userweb, 'show', null);
					setTimeout(function() {
					$.openWindow({
						id: 'settingpage',
						url: 'http://{{.ServerHost}}:{{.ServerPort}}/setting',

						show: {
							aniShow: 'pop-in'
						},
						waiting: {
							autoShow: false
						}
					});
					}, 0);
					mui.back();
				};
				//检查 "登录状态/锁屏状态" 开始
		 		//自动登录改由settingpage加载页面的时候做处理
				app.setState(null);
				//第三方登录
				var authBtns = ['qihoo', 'weixin', 'sinaweibo', 'qq']; //配置业务支持的第三方登录
				var auths = {};
				var oauthArea = doc.querySelector('.oauth-area');
				plus.oauth.getServices(function(services) {
					for (var i in services) {
						var service = services[i];
						auths[service.id] = service;
						if (~authBtns.indexOf(service.id)) {
							var isInstalled = app.isInstalled(service.id);
							var btn = document.createElement('div');
							//如果微信未安装，则为不启用状态
							btn.setAttribute('class', 'oauth-btn' + (!isInstalled && service.id === 'weixin' ? (' disabled') : ''));
							btn.authId = service.id;
							btn.style.backgroundImage = 'url("../../static/img/images/' + service.id + '.png")'
							oauthArea.appendChild(btn);
						}
					}

					$(oauthArea).on('tap', '.oauth-btn', function() {
						if (this.classList.contains('disabled')) {
							plus.nativeUI.toast('您尚未安装微信客户端');
							return;
						}
						var auth = auths[this.authId];
						var waiting = plus.nativeUI.showWaiting();
						auth.login(function() {
							waiting.close();
							plus.nativeUI.toast("登录认证成功");

							auth.getUserInfo(function() {
								// plus.nativeUI.toast("获取用户信息成功");

								var name = auth.userInfo.nickname || auth.userInfo.name;
								var authRegInfo = {
										nick:name,
										token:auth.authResult.access_token,
										uname:auth.authResult.openid,
										platform:auth.id
									}	
									
									$.post('http://{{.ServerHost}}:{{.ServerPort}}/regist/checkuname',{
										uName:authRegInfo.uname
									},function(data){
										
										if (data.CanUse) {
											mui.post('http://{{.ServerHost}}:{{.ServerPort}}/regist/reginfo', {
												uname: authRegInfo.uname,
												pw: authRegInfo.token,
												nickname: authRegInfo.nick,
												platform:authRegInfo.platform
											}, function(data) {
												if (data.result) {
													mui.toast('注册成功！');
													mui.post('http://{{.ServerHost}}:{{.ServerPort}}/login/addonline',{
														uname:authRegInfo.uname,
														token:authRegInfo.token
													},function(data){
														if (data.rel != 0) {
															if (data.rel == 1) {
																$.toast("账号错误...");
															} else if (data.rel == 2) {
																$.toast("密码错误...");
															}
														} else if (data.rel == 0) {
															app.createState(authRegInfo, function() {
																var character = {
																	uname:authRegInfo.uname,//为了显示好看特殊修改
																	nick:authRegInfo.nick,
																	qqnum:'',
																	phone:'',
																	email:'',
																	token:authRegInfo.token,
																	platform:authRegInfo.platform
																}

																app.login(character, function(err) {
																	if (err) {
																		plus.nativeUI.toast(err);
																		return;
																	}
																	toUser();
																});
															});
														} else {
															alert('用户登录数据有误,错误码：'+data.rel);
														}

													},'json');														
												} else {
													mui.toast('注册失败！');
												}
											}, 'json');
										}else{
											mui.post('http://{{.ServerHost}}:{{.ServerPort}}/login/addonline',{
												uname:authRegInfo.uname,
												token:authRegInfo.token
											},function(data){
												if (data.rel != 0) {
														if (data.rel == 1) {
															$.toast("账号错误...");
														} else if (data.rel == 2) {
															$.toast("密码错误...");
														}
													} else if (data.rel == 0) {
														app.createState(authRegInfo, function() {
															var character = {
																uname:authRegInfo.uname,//为了显示好看特殊修改
																nick:authRegInfo.nick,
																qqnum:'',
																phone:'',
																email:'',
																token:authRegInfo.token,
																platform:authRegInfo.platform
															}

															app.login(character, function(err) {
																if (err) {
																	plus.nativeUI.toast(err);
																	return;
																}
																toUser();
															});
														});
												} else {
													alert('用户登录数据有误,错误码：'+ data.rel);
												}
											},'json');
										}
									},'json');

							}, function(e) {
								plus.nativeUI.toast("获取用户信息失败：" + e.message);
							});
						}, function(e) {
							waiting.close();
							plus.nativeUI.toast("登录认证失败：" + e.message);
						});
					});
				}, function(e) {
					oauthArea.style.display = 'none';
					plus.nativeUI.toast("获取登录认证失败：" + e.message);
				});
			
				
				// close splash
				setTimeout(function() {
					//关闭 splash
					plus.navigator.closeSplashscreen();
				}, 600);
				
				//检查 "登录状态/锁屏状态" 结束
				var loginButton = doc.getElementById('login');
				var unameBox = doc.getElementById('uname');
				var passwordBox = doc.getElementById('password');
				var autoLoginButton = doc.getElementById("autoLogin");
				var regButton = doc.getElementById('reg');
				var forgetButton = doc.getElementById('forgetPassword');

				loginButton.addEventListener('tap', function(event) {
					var loginInfo = {
						uname: unameBox.value,
						password: passwordBox.value
					};//普通登录

					mui.post('http://{{.ServerHost}}:{{.ServerPort}}/login/userlogin',{
						uname:loginInfo.uname,
						password:loginInfo.password
					},function(data){
						if (data.rel != 0) {
							if (data.rel == 1) {
								$.toast("账号错误...");
							} else if (data.rel == 2) {
								$.toast("密码错误...");
							}
						} else {
							var character = {
								uname:data.uname,
								nick:data.nick,
								qqnum:data.qq,
								phone:data.phone,
								email:data.email,
								token:data.token,
								platform:'self'
							}

							var stateInfo = {
									nick:data.nick,
									token:data.token,
									uname:data.uname,
									platform:'self'
							}

							mui.post('http://{{.ServerHost}}:{{.ServerPort}}/login/addonline',{
								uname:data.uname,
								token:data.token
							},function(data){
								if (data.rel == 0) {
									app.createState(stateInfo, function() {
										var character = {
											uname:stateInfo.uname,
											nick:stateInfo.nick,
											qqnum:'',
											phone:'',
											email:'',
											token:stateInfo.token,
											platform:stateInfo.platform
										}

										app.login(character, function(err) {
											if (err) {
												plus.nativeUI.toast(err);
												return;
											}
											toUser();
										});
									});
								} else {
									alert('用户登录数据有误,错误码：'+ data.rel);
								}
							},'json');
						}
					},'json');			
				});

				$.enterfocus('#login-form input', function() {
					$.trigger(loginButton, 'tap');
				});
				autoLoginButton.classList[settings.autoLogin ? 'add' : 'remove']('mui-active')
				autoLoginButton.addEventListener('toggle', function(event) {
					setTimeout(function() {
						var isActive = event.detail.isActive;
						settings.autoLogin = isActive;
						app.setSettings(settings);
					}, 50);
				}, false);
				regButton.addEventListener('tap', function(event) {
					$.openWindow({
						url: 'http://{{.ServerHost}}:{{.ServerPort}}/regist',
						id: 'registpage',
						preload: true,
						show: {
							aniShow: 'pop-in'
						},
						styles: {
							popGesture: 'hide'
						},
						waiting: {
							autoShow: false
						}
					});
				}, false);
				forgetButton.addEventListener('tap', function(event) {
					$.openWindow({
						url: 'forget_password.html',
						id: 'forget_password',
						preload: true,
						show: {
							aniShow: 'pop-in'
						},
						styles: {
							popGesture: 'hide'
						},
						waiting: {
							autoShow: false
						}
					});
				}, false);
				
				window.addEventListener('resize', function() {
					oauthArea.style.display = document.body.clientHeight > 400 ? 'block' : 'none';
				}, false);
				
				// var backButtonPress = 0;
				// $.back = function(event) {
				// 	backButtonPress++;
				// 	if (backButtonPress > 1) {
				// 		plus.runtime.quit();
				// 	} else {
				// 		plus.nativeUI.toast('再按一次退出应用');
				// 	}
				// 	setTimeout(function() {
				// 		backButtonPress = 0;
				// 	}, 1000);
				// 	return false;
				// };
			});

			// var loginbackBox = document.getElementById('loginback');
			// loginbackBox.addEventListener('tap',function(){
			// 	var thispage = plus.webview.currentWebview();
			// 	thispage.hide();
			// });
		}(mui, document));
		</script>
	</body>
</html>